<?php
namespace ApplicationTest;

use Core\Config;
use Logger;
use Zend\Loader\AutoloaderFactory;
use Zend\Mvc\Service\ServiceManagerConfig;
use Zend\ServiceManager\ServiceManager;
use Zend\Stdlib\ArrayUtils;

error_reporting(E_ALL | E_STRICT);
chdir(__DIR__);

include __DIR__.'/../application/config/startup.php';
class TestBootstrap
{
    /**
     * @var ServiceManager
     */
    protected static $serviceManager;
    protected static $config;
    protected static $bootstrap;

    public static function init()
    {
        // Load the user-defined test configuration file, if it exists; otherwise, load
        if (is_readable(__DIR__ . '/TestConfig.php')) {
            $testConfig = include __DIR__ . '/TestConfig.php';
        } else {
            $testConfig = include __DIR__ . '/TestConfig.php.dist';
        }

        $zf2ModulePaths = array();

        if (isset($testConfig['module_listener_options']['module_paths'])) {
            $modulePaths = $testConfig['module_listener_options']['module_paths'];
            foreach ($modulePaths as $modulePath) {
                if (($path = static::findParentPath($modulePath)) ) {
                    $zf2ModulePaths[] = $path;
                }
            }
        }

        $zf2ModulePaths  = implode(PATH_SEPARATOR, $zf2ModulePaths) . PATH_SEPARATOR;
        $zf2ModulePaths .= getenv('ZF2_MODULES_TEST_PATHS') ?: (defined('ZF2_MODULES_TEST_PATHS') ? ZF2_MODULES_TEST_PATHS : '');

        static::initAutoloader();

        // use ModuleManager to load this module and it's dependencies
        $baseConfig = array(
            'module_listener_options' => array(
                'module_paths' => explode(PATH_SEPARATOR, $zf2ModulePaths),
            ),
        );

        $config = ArrayUtils::merge($baseConfig, $testConfig);

        $serviceManager = new ServiceManager(new ServiceManagerConfig());
        $serviceManager->setService('ApplicationConfig', $config);
        $serviceManager->get('ModuleManager')->loadModules();

        self::initLogger();

        static::$serviceManager = $serviceManager;
        static::$config = $config;
    }

    /**
     * @return ServiceManager
     */
    public static function getServiceManager()
    {
        return static::$serviceManager;
    }

    public static function getConfig()
    {
        return static::$config;
    }

    protected static function initAutoloader()
    {
       /* $vendorPath = static::findParentPath('vendor');

        if (is_readable($vendorPath . '/autoload.php')) {
            $loader = include $vendorPath . '/autoload.php';
        } else {
            $zf2Path = getenv('ZF2_PATH') ?: (defined('ZF2_PATH') ? ZF2_PATH : (is_dir($vendorPath . '/ZF2/library') ? $vendorPath . '/ZF2/library' : false));

            if (!$zf2Path) {
                throw new RuntimeException('Unable to load ZF2. Run `php composer.phar install` or define a ZF2_PATH environment variable.');
            }

            include $zf2Path . '/Zend/Loader/AutoloaderFactory.php';

        }*/
        include __DIR__. '/../library/Zend/Loader/AutoloaderFactory.php';


        AutoloaderFactory::factory(array(
            'Zend\Loader\StandardAutoloader' => array(
                'autoregister_zf' => true,
                'namespaces' => array(
                    __NAMESPACE__ => __DIR__ . '/' . __NAMESPACE__,

                ),
            ),
        ));

        require_once __DIR__. '/../library/Zend/Loader/ClassMapAutoloader.php';
        $loader = new \Zend\Loader\ClassMapAutoloader(array(

            __DIR__. '/../library/Core/autoload_classmap.php',

        ));
        $loader->register();

    }

    protected static function findParentPath($path)
    {
        $dir = __DIR__;
        $previousDir = '.';
        while (!is_dir($dir . '/' . $path)) {
            $dir = dirname($dir);
            if ($previousDir === $dir) return false;
            $previousDir = $dir;
        }
        return $dir . '/' . $path;
    }

    private static function initLogger()
    {
        Logger::resetLoggers();

        // try to load configuration
        $conf = Config::getSystemConfig();
        /*
                if ($conf) {
                    //firephp logger
                    if ($conf->general->firephp) {
                        $writerFirebug = new Zend\Log\Writer\FirePhp();
                        $loggerFirebug = new Zend\Log\Logger();
                        $loggerFirebug->addWriter($writerFirebug);
                        Logger::addLogger($loggerFirebug);
                    }
                }*/


        if (!is_file(CORE_LOG_DEBUG)) {
            if (is_writable(dirname(CORE_LOG_DEBUG))) {
                file_put_contents(CORE_LOG_DEBUG, "AUTOCREATE\n");
            }
        }

        if (is_writable(CORE_LOG_DEBUG)) {

            // check for big logfile, empty it if it's bigger than about 200M
            if (filesize(CORE_LOG_DEBUG) > 100000000) {
                file_put_contents(CORE_LOG_DEBUG, "");
            }

            $prioMapping = array(
                "debug" => \Zend\Log\Logger::DEBUG,
                "info" => \Zend\Log\Logger::INFO,
                "notice" => \Zend\Log\Logger::NOTICE,
                "warning" => \Zend\Log\Logger::WARN,
                "error" => \Zend\Log\Logger::ERR,
                "critical" => \Zend\Log\Logger::CRIT,
                "alert" => \Zend\Log\Logger::ALERT,
//                "emergency" => Zend\Log\Logger::EMERG
            );

            $prios = array();

            if ($conf && $conf->general->loglevel) {
                $prioConf = $conf->general->loglevel->toArray();
                if (is_array($prioConf)) {
                    foreach ($prioConf as $level => $state) {
                        if ($state) {
                            $prios[] = $prioMapping[$level];
                        }
                    }
                }
            }
            else {
                // log everything if config isn't loaded (eg. at the installer)
                foreach ($prioMapping as $p) {
                    $prios[] = $p;
                }
            }

            if (!empty($prios)) {
                $writerFile = new \Zend\Log\Writer\Stream(CORE_LOG_DEBUG);
                $loggerFile = new \Zend\Log\Logger();
                $loggerFile->addWriter($writerFile);

                Logger::addLogger($loggerFile);

                Logger::setPriorities($prios);
            }



        }
}



}

TestBootstrap::init();